<!--
*@description 待接诊列表
*@fileName recept-list.vue
*@author wxl
*@date 2025/05/06 10:50:41
!-->
<template>
  <div class="" >
    <el-row class="row-container">
      <el-col :span="7" style="height: 100%">
        <div class="left-card c-card">
          <!-- 接诊详情弹窗 -->
          <div class="detail-pop" v-if="showDetail">
            <div class="head fs16">
              问诊订单详情
              <el-icon @click="showDetail = false" class="close cursor" size="20"><el-icon-Close /></el-icon>
            </div>
            <div class="text-bold fs24 text-center">{{ getDictName(orderInfo.IsPrescription, 'IsPrescription') }}</div>
            <div class="row">
              <div class="aicjcsb margin-top">
                <el-tag class="margin-bottom" type="primary" size="small">患者信息</el-tag>
                <el-tag class="margin-bottom" type="info">{{ getDictName(orderInfo.CirculationType, 'CirculationType') }}</el-tag>
              </div>
              <div class="df">
                <div class="col">
                  <div>患者姓名：{{ orderInfo.psn_name }}</div>
                  <div>性别：{{ getDictName(orderInfo.sex, 'sex') }}</div>
                  <div>问诊类型：{{ getDictName(orderInfo.ConsultationMethod, 'ConsultationMethod') }}</div>
                </div>
                <div class="col">
                  <div>手机号码：{{ orderInfo.phone }}</div>
                  <div>年龄：{{ orderInfo.age }}</div>
                  <div>处方类型：{{ getDictName(orderInfo.PrescriptionType, 'PrescriptionType') }}</div>
                </div>
              </div>
              <div class="margin-bottom-sm">临床诊断：{{ orderInfo.Symptom }}</div>
              <div>问诊药店：{{ orderInfo.fixmedins_name }}</div>
            </div>
            <div class="row">
              <el-tag class="margin-bottom" type="primary" size="small">药品信息</el-tag>
              <div class="aicjcsb margin-bottom-sm" v-for="(item, index) in orderInfo.medicineList" :key="index">
                <div>{{ item.ItemName }} <span v-if="orderInfo.PrescriptionType == 1">{{ item.spec }}/{{ item.minPackagingQuantity }} {{ item.minPreparationUnt }}</span> </div>
                <div>X{{ item.DrugNum }} {{ orderInfo.PrescriptionType == 2 ? 'g' : '' }}</div>
              </div>
            </div>
            <div class="row">
              <el-tag class="margin-bottom" type="primary" size="small">过往史</el-tag>
              <div class="aicjcsb margin-bottom-sm">
                <div>是否用过此药物</div>
                <div>{{ orderInfo.IsTake == 1 ? '是' : '否' }}</div>
              </div>
              <div class="aicjcsb margin-bottom-sm">
                <div>是否有药物过敏史</div>
                <div>{{ orderInfo.IsAllergy == 1 ? '是' : '否' }}</div>
              </div>
              <div class="aicjcsb margin-bottom-sm">
                <div>肝肾功能是否异常</div>
                <div>{{ orderInfo.IsLiverRenalFunctionAbnormity == 1 ? '是' : '否' }}</div>
              </div>
              <div class="aicjcsb">
                <div>有无不良反应</div>
                <div>{{ orderInfo.IsUntowardReaction == 1 ? '是' : '否' }}</div>
              </div>
            </div>
            <div class="foot jccaic padding-tb margin-top-lg">
              <el-button type="danger" plain class="margin-right" @click="showDetail = false">关闭</el-button>
              <el-button type="primary" @click="toPrescribe(orderInfo)" v-if="orderInfo.IsPrescription == 1 || orderInfo.IsPrescription == 3">去开方</el-button>
            </div>
          </div>
          <!-- 接诊患者列表 -->
          <div class="patient-list" v-show="!showDetail">
            <div class="c-title">接诊台</div>
            <el-collapse v-model="activeNames">
              <el-collapse-item v-for="(item, index) in patientList" :key="index" :name="item.key">
                <template #title>
                  <div class="aic">
                    <img class="icon" :src="item.icon" alt="" />
                    <div>{{ item.name }}</div>
                    <div>({{ item.list.length || 0 }})</div>
                  </div>
                </template>
                <div
                  class="patient-item aicjcsb pointer"
                  v-for="(patient, pIndex) in item.list"
                  :key="pIndex"
                  :class="index < 2 ? '' : 'uncheck'"
                  @click="seeDetail(patient)"
                >
                  <el-avatar :class="index < 2 ? 'bg-blue' : ''"> {{ patient.psn_name.substr(0, 1) }} </el-avatar>
                  <div class="flex1 margin-lr-sm">
                    <div class="aic">
                      <div>{{ patient.psn_name }} / {{ patient.sex == '1' ? '男' : '女' }} / {{ patient.age }}岁</div>
                      <el-tag class="margin-left-sm" :type="index < 2 ? 'primary' : 'info'" size="small">{{
                        patient.ConsultationMethod == 1 ? '图文问诊' : '视频问诊'
                      }}</el-tag>
                    </div>
                    <div class="text-gray fs12 margin-top-xs aicjcsb">
                      <span> #{{ patient.Symptom }}</span>
                      <span v-if="index != 0">{{ patient.CreateDT }}</span>
                      <!-- <div v-for="(tag, tIndex) in patient.tag" :key="tIndex">{{ tag }}</div> -->
                    </div>
                  </div>
                  <div class="text-primary fs14" v-if="patient.IsPrescription == 1 || patient.IsPrescription == 3" @click.stop="toPrescribe(patient)">去开方</div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </div>
      </el-col>
      <!-- 右侧面板 -->
      <el-col :span="17" style="height: 100%;">
        <div class="cdf right-pannel"  v-if="showRight">
          <div class="c-card right-patient">
            <div class="item" v-for="(item, index) in infoCfg" :key="index">
              <div class="label">{{ item.label }}</div>
              <div class="value">{{ item.formatter ? item.formatter(orderInfo[item.key]) : orderInfo[item.key] }}</div>
            </div>
            <div class="item aic" style="flex:1">
              <div class="label">诊断信息</div>
              <el-select
                class="flex1"
                v-model="orderInfo.diag_code_arr"
                filterable
                remote
                reserve-keyword
                placeholder="输入诊断信息"
                :remote-method="remoteMethod"
                :loading="remoteLoading"
                @change="selectChange"
              >
                <el-option
                  v-for="item in diagOptions"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
            </el-select>
            </div>
            <div class="item aic">
              <div class="label">开具时间</div>
              <el-date-picker
                class="flex1"
                v-model="orderInfo.electronicPrescriptionTime"
                type="date"
                placeholder="选择日期时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </div>
          </div>
          <div class="c-card flex1 cdf" style="overflow-y: auto;">
            <div class=" aicjcsb">
              <div class="c-title">药品清单</div>
              <el-button type="primary" size="small" @click="openDrugDialog" :disabled="medicineList.length >= 5  && orderInfo.PrescriptionType == 1">新增药品</el-button>
            </div>
            <div class="table flex1">
              <!-- 中药 -->
              <el-table :data="medicineList" style="width: 100%" v-if="orderInfo.PrescriptionType == 2">
                <!-- 第一列显示序号 -->
                <el-table-column label="序号" type="index" width="auto"></el-table-column>
                <el-table-column label="药品名称" prop="ItemName">
                  <template #default="{ row }">
                    <el-input v-model="row.ItemName" placeholder="请输入药品名称" />
                  </template>
                </el-table-column>
                <el-table-column label="药品数量" prop="DrugNum">
                  <template #default="{ row }">
                    <el-input-number v-model="row.DrugNum" :min="0" placeholder="请输入数量" controls-position="right" />
                    <span class="margin-left">g</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ row, $index }">
                    <el-button type="danger" size="small" @click="deleteMedicine($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 西药 -->
              <el-table :data="medicineList" style="width: 100%" v-else>
                <!-- 第一列显示序号 -->
                <!-- <el-table-column label="序号" type="index" width="60"></el-table-column> -->
                <el-table-column label="药品名称" prop="ItemName">
                  <template #default="{ row }">
                    <el-input v-model="row.ItemName" placeholder="请输入药品名称" />
                  </template>
                </el-table-column>
                <el-table-column label="药品数量" prop="DrugNum" >
                  <template #default="{ row }">
                    <el-input-number v-model="row.DrugNum" :min="0" style="width: 90px;"  placeholder="请输入数量" controls-position="right" />
                  </template>
                </el-table-column>
                <el-table-column label="规格" width="90">
                  <template #default="{ row }">
                    <div>
                      {{ row.spec }}
                      <span>/{{ row.minPackagingQuantity }}</span
                      ><span>{{ row.minPreparationUnt }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="每次用量" width="160">
                  <template #default="{ row }">
                    <div class="aic">
                      <el-input type="number" v-model="row.sinDoscnt" placeholder="请输入" />
                      <el-select v-model="row.sinDosunt" placeholder="请选择" class="margin-left-xs" style="width: 100px;">
                        <el-option v-for="item in dict.unitRange" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="频率">
                  <template #default="{ row }">
                    <div class="aic">
                      <el-select v-model="row.used_frqu_dscr" placeholder="请选择" >
                        <el-option v-for="item in dict.frequencyOptions" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="用法">
                  <template #default="{ row }">
                    <div class="aic">
                      <el-select v-model="row.usageDosage" placeholder="请选择">
                        <el-option v-for="item in dict.administrationOptions" :key="item.value" :label="item.label" :value="item.value" />
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="可服用天数">
                  <template #default="{ row }">
                    <el-input  placeholder="请输入" style="width: 80px" v-model="row.prd_days" />天
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ row, $index }">
                    <el-button type="danger" size="small" @click="deleteMedicine($index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>

              
              <el-form class="margin-top" :model="medicineForm" label-width="80" :rules="medicineRules" ref="medicineRef" inline v-if="orderInfo.PrescriptionType == 2">
                <el-form-item label="总剂量" prop="cmDrugNum">
                  <el-input v-model="medicineForm.cmDrugNum" style="width: 120px;" />
                </el-form-item>
                <el-form-item label="用法" prop="cmused_mtd">
                  <el-select v-model="medicineForm.cmused_mtd" placeholder="请选择"  style="width: 120px;">
                    <el-option :label="item.label" :value="item.value" v-for="(item, index) in dict.cmused_mtd" :key="index"/>
                  </el-select>
                </el-form-item>
                <el-form-item label="用药频次" prop="cmused_frqu">
                  <el-select v-model="medicineForm.cmused_frqu" placeholder="请选择"  style="width: 120px;">
                    <el-option :label="item.label" :value="item.value" v-for="(item, index) in dict.frequencyOptions" :key="index"/>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div class="jccaic margin-top">
              <el-button class="foot-btn" type="primary" plain @click="confirm(true)">预览</el-button>
              <el-button class="foot-btn" type="primary" :loading="confirmLoading" :disabled="confirmLoading" @click="confirm(false)">确认处方</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    
    <!-- 药品选择弹窗 -->
    <el-dialog v-model="drugDialogVisible" :title="(orderInfo.PrescriptionType == 2 ? '中药' : '西药') + '药品选择'" width="800px" append-to-body>
      <div class="margin-bottom">
        <el-input
          v-model="drugSearchParam.name"
          placeholder="请输入药品名称"
          clearable
          style="width: 200px;"
          @keyup.enter="searchDrugs"
          @input="handleDrugSearchInput"
          class="margin-right"
        >
        </el-input>
        <el-input
          v-model="drugSearchParam.code"
          placeholder="请输入药品编码"
          clearable
          style="width: 200px;"
          @keyup.enter="searchDrugs"
          @input="handleDrugSearchInput"
          class="margin-right"
        >
        </el-input>
        <el-button type="primary"  @click="searchDrugs" >搜索</el-button>
      </div>
      <el-table :data="drugList" style="width: 100%" :row-key="getRowKeys" @selection-change="handleSelectionChange" ref="drugTableRef">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column v-for="col in drugColumns" :key="col.key" :label="col.name" :prop="col.key"></el-table-column>
      </el-table>
      <el-pagination
        class="margin-top text-right"
        v-model:current-page="drugPagination.pageNo"
        v-model:page-size="drugPagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="drugPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="drugDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelectDrug" :disabled="selectedDrugs.length === 0" >确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <prescriptionDialog ref="$prescriptionDialog" :orderInfo="orderInfo" :medicineForm="medicineForm" :signatures="signatures" :medicineListProps="medicineList" :OnlineInquiryId="OnlineInquiryId"></prescriptionDialog>
  </div>
</template>
<script setup>
import icon1 from '@/assets/wait.png'
import icon2 from '@/assets/pend.png'
import icon3 from '@/assets/success.png'
import dict from '@/utils/dict.js'
import prescriptionDialog from '@/components/prescription-dialog/prescription-dialog.vue'
import {ElMessage} from "element-plus";
import { onActivated, ref, computed, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { useNewsStore } from '@/store/news'
import commonJs from '@/utils/common.js'

const newsStore = useNewsStore()
const route = useRoute()
const pagin = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  server_time: '',
})

const activeNames = ref(['wait'])
const showDetail = ref(false) // 是否查看问诊订单详情
const orderInfo = ref({}) // 问诊订单详情
const medicineList = ref([]) // 药店开方药品列表
const showRight = ref(false) // 是否展示右侧开方
const OnlineInquiryId = ref('') 
const $prescriptionDialog = ref(null)
const remoteLoading = ref(false)
const diagOptions  = ref([])
const medicineRef = ref(null)
const confirmLoading =  ref(false)
const signatures = ref({})
// 中药用法等表单
const medicineForm = ref({
  cmDrugNum: '',
  cmused_mtd: '',
  cmused_frqu: '',
})
const medicineRules = {
  cmDrugNum: [{ required: true, message: '请输入总剂量', trigger: 'blur' }],
  cmused_mtd: [{ required: true, message: '请选择用法', trigger: 'change' }],
  cmused_frqu: [{ required: true, message: '请输入用药频次', trigger: 'blur' }],
}

// 药品选择弹窗相关
const drugDialogVisible = ref(false)
// 药品搜索防抖定时器
const drugSearchDebounceTimer = ref(null)
const drugList = ref([])
const drugPagination = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
})
const selectedDrugs = ref([]) // 存储已选择的药品
const drugTableRef = ref(null) // 药品表格引用
const drugSearchParam = reactive({
  name: '',
  code: ''
})
const getRowKeys = (row) => {
  return row.med_list_codg
}
// 西药字段配置
const wmDrugColumns = [
  {
    name: '药品代码',
    key: 'med_list_codg'
  },
  {
    name: '注册名称',
    key: 'reg_nam'
  },
  {
    name: '注册剂型',
    key: 'reg_dosform'
  },
  {
    name: '注册规格',
    key: 'reg_spec'
  },
  {
    name: '生产企业',
    key: 'EnterpriseName'
  }
]

// 中药字段配置
const cmDrugColumns = [
  {
    name: '药品名称',
    key: 'ver_name'
  },
  {
    name: '药品编码',
    key: 'med_list_codg'
  }
]

const drugColumns = computed(() => {
  return orderInfo.value.PrescriptionType == 2 ? cmDrugColumns : wmDrugColumns
})

const patientList = ref([
  {
    name: '候诊患者',
    key: 'wait',
    num: 2,
    icon: icon1,
    listKey: 'data',
    list: [],
  },
  {
    name: '接诊中',
    key: 'pend',
    num: 1,
    icon: icon2,
    listKey: 'data1',
    list: [],
  },
  {
    name: '今日已诊患者',
    key: 'success',
    num: 3,
    icon: icon3,
    listKey: 'data2',
    list: [],
  },
])
const infoCfg = ref([
  {
    label: '患者姓名',
    key: 'psn_name',
  },
  {
    label: '身份证号码',
    key: 'mdtrt_cert_no',
  },
  {
    label: '手机号码',
    key: 'phone',
  },
  {
    label: '性别',
    key: 'sex',
    formatter: (value) => {
      return dict.sex.find((item) => item.value == value)?.label
    },
  },
  {
    label: '年龄',
    key: 'age',
  },
  {
    label: '临床诊断',
    key: 'Symptom',
  },
  {
    label: '病种类型',
    key: 'CirculationType',
    formatter: (value) => {
      return dict.CirculationType.find((item) => item.value == value)?.label
    },
  },
  {
    label: '处方类型',
    key: 'PrescriptionType',
    formatter: (value) => {
      return dict.PrescriptionType.find((item) => item.value == value)?.label || '西药处方'
    },
  },
  {
    label: '问诊药店',
    key: 'fixmedins_name',
  },
  {
    label: '问诊时间',
    key: 'CreateDT',
  },
  // {
  //   label: '诊断信息',
  //   key: 'diag_name',
  // },
])
// 监听是否有新订单
watch(() => newsStore.hasNewOrder, (newVal) => {
  if(newVal) {
    f5()
  }
})
// 使用 watch 监听路由参数变化
watch(() => route.query, (newQuery, oldQuery) => {
  console.log('route===',route)
  if (newQuery.OnlineInquiryId !== oldQuery.OnlineInquiryId) {
    console.log(`watch检测到路由参数变化:`);
    init()
  }
});
// 组件加载时触发
onMounted(() => {
  console.log(123 + 'onMounted')
  // 获取参数 初始化
  init()
  f5()
  getDiagType()
})

// 搜索
function onSearch() {
  pagin.pageNo = 1
  f5()
}

async function init() { 
  let params = route.query
  console.log('params',params)
  if(params.OnlineInquiryId) {
    await getDetail(params.OnlineInquiryId)
    showDetail.value = true
    showRight.value = true
  }
}
// ------------------ 查找数据 ------------------
const f5 = function () {
  let params = {
    pageindex: pagin.pageNo - 1,
    pagesize: pagin.pageSize,
  }
  sa.ajax('/api/webOnlineInquiry/waitingOnlineInquiryList', params, function (res) {
    // tableData.value = res.data;	// 数据
    if (res.code == '1') {
      // 刷新订单标识
      newsStore.setHasNewOrder(false)
      patientList.value.forEach((item) => {
        item.list = res[item.listKey] || []
      })
    }
  })
}
// 获取诊断信息列表
const getDiagType = function (name) {
  let params = {
    pageindex: 0,
    pagesize: 100,
    name: name || ''
  }
  sa.ajax('/api/DiagCatalogue/list', params, function (res) {
    // tableData.value = res.data;	// 数据
    if (res.code == '1') {
      remoteLoading.value = false
      diagOptions.value = res.data
    }
  })
}


// 远程
function remoteMethod(query) {
  remoteLoading.value = true
  getDiagType(query)
}
// 诊断信息选择后回调
function selectChange(e) {
  console.log('eee',e)
  let name = [] 
  diagOptions.value.forEach(item => {
    if(e == item.code) {
      name.push(item.name)
    }
  })
  orderInfo.value.diag_name = name.join(',')
  orderInfo.value.diag_code = e
  console.log('orderInfo.value',orderInfo.value)
}
// 查看详情
async function seeDetail(patient) {
  console.log('item', patient)
  await getDetail(patient.OnlineInquiryId)
  showDetail.value = true
  if(patient.OnlineInquiryId != orderInfo.value.OnlineInquiryId) {
    showRight.value = false
  }
}

const getDetail = function (OnlineInquiryId) {
  let params = {
    OnlineInquiryId,
  }
  sa.ajax('/api/webOnlineInquiry/onlineInquiryDetail', params, function (res) {
    // tableData.value = res.data;	// 数据
    if (res.code == '1') {
      orderInfo.value = res.data || {}
      orderInfo.value.medicineList = res.data1 || []
      orderInfo.value.electronicPrescriptionTime = res.data.electronicPrescriptionTime || commonJs.formatDate(Date.now(),'yyyy-MM-dd')
      medicineList.value = JSON.parse(JSON.stringify(res.data1 || []))
      signatures.value = res.data2 || {}
    }
  })
}

// 去开方
async function toPrescribe(patient) {
  OnlineInquiryId.value = patient.OnlineInquiryId
  // 清空表单
  medicineForm.value = {
    cmDrugNum: '',
    cmDrugName: '',
    cmDrugSpec: '',
  }
  if (!showDetail.value) {
    await getDetail(patient.OnlineInquiryId)
  } else {
  }
  showRight.value = true
}

// 获取字典值
function getDictName(value, dictType) {
  try {
    return dict[dictType].find((item) => item.value == value).label
  } catch (error) {
    return ''
  }
}

// 确认处方
async function confirm(isPreview = false) {
  // 判断是否有诊断信息
  if (!orderInfo.value.diag_code_arr) {
    ElMessage.error('请填写诊断信息')
    return
  }
  
  // 校验药品清单中的每个药品信息
  let valid = true
  for (let i = 0; i < medicineList.value.length; i++) {
    const medicine = medicineList.value[i]
    
    // 校验药品名称
    if (!medicine.ItemName) {
      ElMessage.error(`第${i+1}行药品名称不能为空`)
      valid = false
      break
    }
    
    // 校验药品数量
    if (!medicine.DrugNum || medicine.DrugNum <= 0) {
      ElMessage.error(`第${i+1}行药品数量必须大于0`)
      valid = false
      break
    }
    
    // 如果是西药，校验其他必填项
    if (orderInfo.value.PrescriptionType != 2) {
      if (!medicine.sinDoscnt) {
        ElMessage.error(`第${i+1}行每次用量不能为空`)
        valid = false
        break
      }
      
      if (!medicine.sinDosunt) {
        ElMessage.error(`第${i+1}行每次用量单位不能为空`)
        valid = false
        break
      }
      
      if (!medicine.used_frqu_dscr) {
        ElMessage.error(`第${i+1}行频率不能为空`)
        valid = false
        break
      }
      
      if (!medicine.usageDosage) {
        ElMessage.error(`第${i+1}行用法不能为空`)
        valid = false
        break
      }
    }
  }
  
  if (!valid) {
    return
  }
  
  let extraParams = {}
  // 中药
  if(orderInfo.value.PrescriptionType == 2) {
    let res = await medicineRef.value.validate()
    console.log('res',res)
    if(!res) return
    extraParams = {
      cmDrugNum: medicineForm.value.cmDrugNum,
      cmused_mtd: medicineForm.value.cmused_mtd,
      cmused_frqu: medicineForm.value.cmused_frqu,
    }
  }
  $prescriptionDialog.value?.show(isPreview)
  // 如果是预览 不需要确认处方请求
  if(isPreview) return 
  sa.loading('正在生成处方...');
  confirmLoading.value = true
  setTimeout(async() => {
    let accessoryId = await $prescriptionDialog.value?.transPrescription()
    console.log('accessoryId',accessoryId)
    let params = {
      OnlineInquiryNo: orderInfo.value.OnlineInquiryNo,
      OnlineInquiryItems: medicineList.value,
      diag_name: orderInfo.value.diag_name,
      diag_code: orderInfo.value.diag_code,
      electronicPrescriptionTime: orderInfo.value.electronicPrescriptionTime,
      ...extraParams,
      accessoryId,
    }
    console.log('params',params)
    // /api/webOnlineInquiry/confirmPres
    sa.ajax('/api/webOnlineInquiry/confirmPresWtihGeneratePres', params, function (res) {
      // tableData.value = res.data;	// 数据
      confirmLoading.value = false
      if (res.code == '1') {
        ElMessage.success('处方确认成功')
        afterClose()
      }
    })
    setTimeout(() => {
      confirmLoading.value = false
    }, 1000)
  }, 100)
}

// 处方流转后
function afterClose() {
  showRight.value = false 
  f5()
  // 如果有打开详情面板  需要刷新详情面板
  if(showDetail.value) {
    getDetail(orderInfo.value.OnlineInquiryId)
  }
}

// 打开药品选择弹窗
function openDrugDialog() {
  if (medicineList.value.length >= 5 && orderInfo.value.PrescriptionType == 1) {
    ElMessage.warning('药品数量已达上限（5个）')
    return
  }
  
  drugDialogVisible.value = true
  selectedDrugs.value = []
  drugSearchParam.code = ''
  drugSearchParam.name = ''
  drugPagination.pageNo = 1
  getDrugList()
  
  // 延迟设置已选中的药品项（确保表格已渲染）
  setTimeout(() => {
    setTableSelection()
  }, 100)

}

// 获取药品列表
function getDrugList() {
  const params = {
    pageindex: drugPagination.pageNo - 1,
    pagesize: drugPagination.pageSize,
    ...drugSearchParam,
    fixmedins_code: orderInfo.value.fixmedins_code
  }
  let platform = import.meta.env.VITE_PLATFORM
  console.log('platform',platform)
  let chineseApiUrl = platform == 'ylyb' ? '/api/CMDPCatalogue/list' : '/api/webPresAdmin/CMDPCatalogueList'
  let westernApiUrl = platform == 'ylyb' ? '/api/WMCPMCatalogue/list' : '/api/webPresAdmin/WMCPMCatalogueList'
  let apiUrl = orderInfo.value.PrescriptionType == 2 ? chineseApiUrl : westernApiUrl

  // const apiUrl = orderInfo.value.PrescriptionType == 2 
  //   ? '/api/webPresAdmin/CMDPCatalogueList' 
  //   : '/api/webPresAdmin/WMCPMCatalogueList'
  
  sa.ajax(apiUrl, params, function(res) {
    if (res.code == '1') {
      drugList.value = res.data || []
      drugPagination.total = Number(res.totalItems) || 0
      
      // 延迟设置已选中的药品项（确保表格已渲染）
      // setTimeout(() => {
      //   setTableSelection()
      // }, 100)
    }
  })
}

// 设置表格选中项
function setTableSelection() {
  if (!drugTableRef.value) return
  
  // 清空当前选中项
  drugTableRef.value.clearSelection()
  
  // 重新设置选中项
  selectedDrugs.value.forEach(selectedDrug => {
    const found = drugList.value.find(drug => 
      drug.med_list_codg === selectedDrug.med_list_codg
    )
    if (found) {
      drugTableRef.value.toggleRowSelection(found, true)
    }
  })
}

// 搜索药品
function searchDrugs() {
  // 清除防抖定时器
  if (drugSearchDebounceTimer.value) {
    clearTimeout(drugSearchDebounceTimer.value)
  }
  drugPagination.pageNo = 1
  getDrugList()
}

// 处理表格选择变化
function handleSelectionChange(selection) {
  selectedDrugs.value = selection
}
// 处理分页大小变化
function handleSizeChange(val) {
  drugPagination.pageSize = val
  getDrugList()
}

// 处理当前页变化
function handleCurrentChange(val) {
  drugPagination.pageNo = val
  getDrugList()
}

// 选择药品（双击行）
function selectDrug(row) {
  selectedDrug.value = row
}

// 确认选择药品
function confirmSelectDrug() {
  if (selectedDrugs.value.length === 0) {
    ElMessage.warning('请先选择药品')
    return
  }
  
  // 检查是否已达到药品数量上限- 西药
  if(orderInfo.value.PrescriptionType == 1) {
    if (medicineList.value.length + selectedDrugs.value.length > 5) {
      ElMessage.warning(`最多只能添加5个药品，当前还可添加${5 - medicineList.value.length}个`)
      return
    }
  }
  
  // 根据处方类型添加不同的药品信息
  // PrescriptionType 2 中药 1 西药
  selectedDrugs.value.forEach(drug => {
    const newMedicine = {
      ItemName:  orderInfo.value.PrescriptionType == 2 ? drug.ver_name: drug.reg_nam,
      DrugNum: 1,
      ItemCode: drug.med_list_codg,
      MIC_Code: drug.med_list_codg,
      // 西药特有字段
      spec: drug.reg_spec || '',
      minPackagingQuantity: drug.minPackagingQuantity,
      minPreparationUnt: drug.minPreparationUnt,
      sinDoscnt: drug.sinDoscnt,
      sinDosunt: drug.sinDosunt,
      used_frqu_dscr: drug.used_frqu_dscr,
      usageDosage: drug.usageDosage,
      prd_days: drug.prd_days,
      OnlineInquiryNo: orderInfo.value.OnlineInquiryNo,
      OnlineInquiryItemId: 0,
      unt: drug.unt || ''
    }
    
    medicineList.value.push(newMedicine)
  })
  
  drugDialogVisible.value = false
  ElMessage.success(`成功添加${selectedDrugs.value.length}个药品`)
  // 清空选择
  selectedDrugs.value = []
}

// 删除药品
function deleteMedicine(index) {
  medicineList.value.splice(index, 1)
  ElMessage.success('药品删除成功')
}

// 药品搜索防抖处理
const handleDrugSearchInput = (field) => {
  // 清除之前的定时器
  if (drugSearchDebounceTimer.value) {
    clearTimeout(drugSearchDebounceTimer.value)
  }
  
  // 设置新的防抖定时器（300ms）
  drugSearchDebounceTimer.value = setTimeout(() => {
    drugPagination.pageNo = 1
    getDrugList()
  }, 500)
}

</script>
<style lang="scss" scoped>
.fs24 {
  font-size: 24px;
}
.row-container {
  height: 100%;
  padding: 15px;
  margin: 0 !important;
  box-sizing: border-box;
  width: 100%;
  overflow: hidden;
  .c-card {
    margin: 0;
  }
  .left-card {
    height: 100%;
    overflow-y: auto;
    position: relative;
    margin-right: 15px;

    &::-webkit-scrollbar {
      // display: none;
    }
    .detail-pop {
      position: absolute;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: #fff;
      .head {
        text-align: center;
        position: relative;
        padding: 20px;
        .close {
          position: absolute;
          right: 15px;
          top: 20px;
          z-index: 2;
        }
      }
      .row {
        padding: 0 20px;
        margin-bottom: 20px;
      }
      .col {
        flex: 0 0 50%;
        font-size: 13px;
        & > div {
          margin-bottom: 10px;
        }
      }
    }
  }
  .patient-list {
    min-width: 320px;
    .icon {
      width: 30px;
      height: 30px;
      margin-right: 5px;
    }
    .patient-item {
      height: 70px;
      background: #f6f8fd;
      border-radius: 8px 8px 8px 8px;
      margin-bottom: 10px;
      padding: 0 20px;
      &.uncheck {
        background: #f8f8f8;
      }
    }
  }
  .right-pannel{
    height: 100%;
  }
  .right-patient {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 15px;
    // &:after{
    //   content: '';
    //   width: 10%;
    //   height: 0;
    // }
    .item {
      flex: 0 0 33%;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
    }
    .label {
      width: 80px;
      text-align: right;
      padding-right: 15px;
      font-size: 13px;
    }
    .value {
      flex: 1;
      height: 35px;
      background: #f6f8fd;
      border-radius: 5px 5px 5px 5px;
      line-height: 38px;
      padding: 0 15px;
      font-size: 13px;
      white-space: nowrap;
    }
  }
  .c-title{
    font-size: 16px;
    position: relative;
  }
  .float-right {
    position: absolute;
    right: 0;
    top: 0;
  }
  .table{
    ::v-deep{
      .el-table .cell{
        padding: 5px;
      }
    }
  }
  
}

</style>